package com.bawei.library_net

import com.bawei.library_net.convert.CustomGsonConverterFactory
import com.bawei.library_net.interceptor.TokenInterceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/19 15:29
 * @Description : RetrofitManager
 */
class RetrofitManager {
    //为了保证是单例模式
    companion object{
        //等价于双重校验锁：kotlin写法
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED){
            RetrofitManager()
        }
    }
    private val retrofit: Retrofit
    init {//单例的init方法只会执行一次
        retrofit = Retrofit.Builder()
            .baseUrl(BuildConfig.SERVER_HOST)
            .client(createOkHttpClient())
            .addConverterFactory(CustomGsonConverterFactory.create())//自定义gson解析器工厂
            .build()
    }
    fun createOkHttpClient():OkHttpClient{


        return OkHttpClient.Builder()
            .readTimeout(60,TimeUnit.SECONDS)
            .writeTimeout(60,TimeUnit.SECONDS)
            .addInterceptor(TokenInterceptor())
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
    }

    //创建对应的Service
    fun <T> create(clazz: Class<*>):T{
        return retrofit.create(clazz) as T
    }


}